package pl.wroc.pwr.docs.repos.webapp.repo;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.h2.fulltext.FullText;
import org.h2.fulltext.FullTextLucene;
import org.h2.jdbcx.JdbcConnectionPool;

@WebListener
public class DatabaseContext implements ServletContextListener {
	private JdbcConnectionPool cp;
	
	@Override
	public void contextInitialized(ServletContextEvent sce) {
        ServletContext context = sce.getServletContext();
        
        String url = context.getInitParameter("db.url.override");
        if(url == null){
        	url = context.getInitParameter("db.url"); 
        }
        System.out.println(url);
        String user = context.getInitParameter("db.user");
        String password = context.getInitParameter("db.password");
  
		cp = JdbcConnectionPool.create(url, user, password);
		cp.setMaxConnections(5);

		context.setAttribute("connectionPool", cp);
		
		try {
			Connection con = cp.getConnection();
			if(!isSchemaCreated(con)){
				createSchema(con);
				createSearchIndex(con);
			}
			con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		cp.dispose();
	}
	
	/*
	 * Testuje czy baza zawiera model 
	 */
	private boolean isSchemaCreated(Connection con) throws SQLException {
		boolean result = false;
		
		String query = "select 1 from Information_schema.tables where table_name = 'DOCUMENTS';";
		
		Statement stmt = con.createStatement();
		ResultSet rs = stmt.executeQuery(query);
		
		// czy jest jeden wiersz i czy jest w nim jedynka
		if (rs.next() && "1".equals(rs.getString("1"))){
			result = true;
		}
		
		return result;
	}
	
	/*
	 * Tworzy model w pustej bazie 
	 */
	private void createSchema(Connection con) throws SQLException {
		String query = "CREATE TABLE documents (" +
	                   "id INT AUTO_INCREMENT PRIMARY KEY, " +
			           "filename VARCHAR(255) NOT NULL, " +
	                   "format VARCHAR(255) NOT NULL, " +
			           "type VARCHAR(255) NOT NULL," +
	                   "created DATETIME, " +
			           "added DATETIME, " +
	                   "title VARCHAR(255), " +
			           "author VARCHAR(70), " +
			           "filepath VARCHAR(255), " +
			           "binary BLOB," +
			           "indexed_content VARCHAR(1000));";
		
		Statement stmt = con.createStatement();
		stmt.execute(query);
	}
	
	/*
	 * inicjuje wyszukiwanie pełnotekstowe
	 */
	private void createSearchIndex(Connection con) throws SQLException {
		final String DEFAULT_SCHEMA = "PUBLIC"; 
		
		FullText.init(con);															//natywne
		FullText.createIndex(con, DEFAULT_SCHEMA, "DOCUMENTS", "INDEXED_CONTENT");
		
		FullTextLucene.init(con);													//Lucene
		FullTextLucene.createIndex(con, DEFAULT_SCHEMA, "DOCUMENTS", "INDEXED_CONTENT");
	}
}